<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div v-if="LoginOrRegister" class="card-header">
          <h1>欢迎登录</h1>
        </div>
        <div v-else class="card-header">
          <h1>欢迎注册</h1>
        </div>
      </template>
      <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="LoginOrRegister?loginRules:rigisterRules"
          :validate-on-rule-change="false"
          class="login-form">
        <el-form-item prop="username" class="content">
          <el-input v-model="loginForm.username"
                    placeholder="用户名"
                    size="large"
                    clearable>
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password"
                    placeholder="密码"
                    size="large"
                    clearable>
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input v-if="!LoginOrRegister" v-model="loginForm.confirmPassword" type="password"
                    placeholder="再次确认密码"
                    size="large"
                    clearable>
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="radio">
          <el-radio-group v-model="loginForm.radio">
            <el-radio :value="3"
                size="large">骑手</el-radio>
            <el-radio :value="6"
                size="large">商家</el-radio>
            <el-radio v-if="LoginOrRegister" :value="9"
                size="large">平台</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button v-if="LoginOrRegister" type="primary" @click="handleLogin"
                  size="large">登录</el-button>
          <el-button type="success" @click="registerForm"
                  size="large">注册</el-button>
          <el-button v-if="!LoginOrRegister" type="danger" @click="backToLogin"
                  size="large">取消</el-button>
          <el-button type="info" @click="backUser"
                     size="large">返回主页</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "../../router.ts";
import storage from '../../storage.ts';


const LoginOrRegister = ref(true);


// 表单引用
const loginFormRef = ref(null)



const backUser = ()=>{
  router.replace({ path: '/user/delivery1' });
}

const backToLogin=()=>{
  loginFormRef.value.resetFields();
  LoginOrRegister.value = true;
}


// 表单数据
const loginForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  radio:null,
})

// 表单验证规则
const loginRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    // { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    // { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  radio: [
    { required: true, message: '请选择用户类型', trigger: 'blur' }
  ]
})

// 表单验证规则
const rigisterRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    // { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    // { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    // { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  radio: [
    { required: true, message: '请选择用户类型', trigger: 'blur' }
  ]
})

// 登录处理函数
const handleLogin = async () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      if(loginForm.radio == 3){
        try {
          const { data } = await axios.post('/api/rider/login', {
            name: loginForm.username,
            pwd: loginForm.password,
          });
          if (data.success) {
            localStorage.setItem('riderId', data.rider.id);

            // 登录成功后
            storage.setUser({
              username: loginForm.username,
              pwd: loginForm.password
            });
            await router.replace({ path: '/rider/profile' });

          } else {
            ElMessage.error(data.message || '登录失败');
          }
        } catch (error) {
          ElMessage.error('网络错误，请稍后重试');
        }



      }
      else if(loginForm.radio == 6){
        try {
          const { data } = await axios.post('/api/shop/login', {
            shopname: loginForm.username,
            pwd: loginForm.password,
          });
          if (data.success) {


            // 登录成功后
            storage.setUser({
              username: loginForm.username,
              pwd: loginForm.password
            });



            // 登录成功，保存token和店铺信息到本地存储
            localStorage.setItem('shopToken', data.token);
            localStorage.setItem('shopInfo', JSON.stringify(data.shop)); // 存储店铺信息
            ElMessage.success('登录成功');

            // 跳转到商户后台首页，并传递店铺ID作为路由参数
            await router.replace({path: '/shop/dishes', query: {id: data.shop.id}});
          } else {
            ElMessage.error(data.message || '登录失败');
          }
        } catch (error) {
          ElMessage.error('网络错误，请稍后重试');
        }
      }
      else if(loginForm.radio == 9){
        try {
          const { data } = await axios.post('/api/admin/login', {
            name: loginForm.username,
            pwd: loginForm.password,
          });
          if (data.success) {
            // 登录成功后
            storage.setUser({
              username: loginForm.username,
              pwd: loginForm.password
            });
            ElMessage.success('登录成功');
            await router.replace({path: '/admin/shop'});

          } else {
            ElMessage.error(data.message || '登录失败');
          }
        } catch (error) {
          ElMessage.error('网络错误，请稍后重试');
        }



      }
    } else {
      console.log('验证失败')
      return false
    }
  })
}

// 注册表单
const registerForm = async () => {

  if(LoginOrRegister.value==false){
    loginFormRef.value.validate(async (valid) => {
      if(valid){
        if(loginForm.radio == 3){

          try {
            const { data } = await axios.post('/api/rider', {
              name: loginForm.username,
              pwd: loginForm.password,
              phone:"",
              gzzt:"0",
              gzsr:0,
              mark:0,
              zcsj:null,
              state:"0",
            });
            if (data) {

              ElMessage.success('注册成功');
              backToLogin();

            } else {
              ElMessage.error(data.message || '注册失败');
            }
          } catch (error) {
            ElMessage.error('网络错误，请稍后重试');
          }

        }
        else if(loginForm.radio == 6){

          try {
            const { data } = await axios.post('/api/shop/register', {
              shopname: loginForm.username,
              pwd: loginForm.password,
            });
            if (data.success) {

              ElMessage.success('注册成功');
              backToLogin();

            } else {
              ElMessage.error(data.message || '注册失败');
            }
          } catch (error) {
            ElMessage.error('网络错误，请稍后重试');
          }

        }
        else if(loginForm.radio == 9){

          try {
            const { data } = await axios.post('/api/admin/register', {
              name: loginForm.username,
              pwd: loginForm.password,
            });
            if (data.success) {

              ElMessage.success('注册成功');
              backToLogin();

            } else {
              ElMessage.error(data.message || '注册失败');
            }
          } catch (error) {
            ElMessage.error('网络错误，请稍后重试');
          }

        }
      }
      else{
        console.log("验证失败");
      }
    },)
  }
  else{
    loginFormRef.value.resetFields();
    LoginOrRegister.value = false;
  }


}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.login-form {
  margin-top: 20px;
}

</style>